<template>
  <MySplitPanes>
    <pane>
      <div class="my-flex-column w100 h100">
        <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
          <el-form :inline="true" label-width="auto" @submit.stop.prevent>
            <el-form-item>
              <my-select-input v-model="state.pageInput.dynamicFilter" :filters="state.filters" @search="onQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
              <el-button type="primary" icon="ele-Search" @click="onFilter"> 高级查询 </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="my-fill mt8" shadow="never">
          <div class="my-tools-box mb8 my-flex my-flex-between">
            <div>
              <el-button v-auth="'api:industry:work-order:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增
              </el-button>
              <el-button v-auth="'api:industry:work-order:import-data'" icon="ele-Download" type="primary"
                @click="onImport"> 导入
              </el-button>
              <el-button v-auth="'api:industry:work-order:export-data'" icon="ele-Upload" type="primary"
                :loading="state.export.loading" @click="onExport">
                导出
              </el-button>
            </div>
            <div>
              <el-tooltip effect="dark" :content="state.showQuery ? '隐藏查询' : '显示查询'" placement="top">
                <el-button :icon="state.showQuery ? 'ele-ArrowUp' : 'ele-ArrowDown'" circle
                  @click="state.showQuery = !state.showQuery" />
              </el-tooltip>
            </div>
          </div>

          <el-table ref="tableRef" v-loading="state.loading" :data="state.workOrderListData" row-key="id" border>
            <el-table-column type="selection" />
            <el-table-column prop="orderCode" label="工单代号" width="100" show-overflow-tooltip />
            <el-table-column prop="orderName" label="工单名称" width="100" show-overflow-tooltip />
            <el-table-column prop="productCode" label="产品编码" width="100" show-overflow-tooltip />
            <el-table-column prop="productName" label="产品名称" width="100" show-overflow-tooltip />
            <el-table-column prop="planCount" label="计划数量" width="100" show-overflow-tooltip />
            <el-table-column prop="successCount" label="完成数量" width="100" show-overflow-tooltip />
            <el-table-column prop="failCount" label="失败数量" width="100" show-overflow-tooltip />
            <el-table-column prop="onLineCount" label="未下线数量" width="100" show-overflow-tooltip />
            <el-table-column prop="planStartDate" label="计划开始时间" width="120" show-overflow-tooltip />
            <el-table-column prop="planEndDate" label="计划结束时间" width="120" show-overflow-tooltip />
            <el-table-column prop="actualStartDate" label="实际开始时间" width="120" show-overflow-tooltip />
            <el-table-column prop="actualEndDate" label="实际结束时间" width="120" show-overflow-tooltip />
            <el-table-column prop="state" label="状态" width="100" show-overflow-tooltip />
            <el-table-column label="操作" width="140" header-align="center" align="center" fixed="right">
              <template #default="{ row }">
                <el-button v-auth="'api:industry:work-order:update'" icon="ele-EditPen" size="small" text type="primary"
                  @click="onEdit(row)">编辑</el-button>
                <my-dropdown-more v-auths="['api:industry:work-order:soft-delete']">
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-if="auth('api:industry:work-order:soft-delete')"
                        @click="onDelete(row)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </my-dropdown-more>
              </template>
            </el-table-column>
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 10px">
            <el-pagination v-model:currentPage="state.pageInput.currentPage"
              v-model:page-size="state.pageInput.pageSize" :total="state.total" :page-sizes="[10, 20, 50, 100]" small
              background @size-change="onSizeChange" @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper" />
          </div>
        </el-card>
        <MyImport ref="workOrderImportRef" :title="state.import.title" v-model="state.import"></MyImport>
        <MyFilterDialog ref="myFilterDialogRef" :fields="state.filters" @sure="onFilterSure"></MyFilterDialog>
      </div>
    </pane>
  </MySplitPanes>
</template>
<script setup lang="ts" name="work-order">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { PageInputWorkOrderGetPageInput, WorkOrderGetPageOutput, WorkOrderGetOutput } from '/@/api/industry/data-contracts'
import { Pane } from 'splitpanes'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import { ElTable } from 'element-plus'
import { WorkOrderApi } from '/@/api/industry/WorkOrder'
import { RequestParams } from '/@/api/admin/http-client'
import dayjs from 'dayjs'


const MyImport = defineAsyncComponent(() => import('/@/components/my-import/index.vue'))
const MySplitPanes = defineAsyncComponent(() => import('/@/components/my-layout/split-panes.vue'))
const MySelectInput = defineAsyncComponent(() => import('/@/components/my-select-input/index.vue'))
const MyDropdownMore = defineAsyncComponent(() => import('/@/components/my-dropdown-more/index.vue'))
const MyFilterDialog = defineAsyncComponent(() => import('/@/components/my-filter/dialog.vue'))

const { proxy } = getCurrentInstance() as any

const workOrderImportRef = ref()
const workOrderFormRef = ref()
const myFilterDialogRef = ref();
const state = reactive({
  loading: false,
  showQuery: true,
  workOrderFormTitle: '',
  total: 0,
  workOrderName: '',
  import: {
    title: '',
    action: import.meta.env.VITE_API_URL + '/api/industry/work-order/import-data',
    downloadTemplate: (params: RequestParams) => new WorkOrderApi().downloadTemplate(params),
    downloadErrorMark: (query: any, params: RequestParams) => new WorkOrderApi().downloadErrorMark(query, params),
    duplicateAction: 1,
    uniqueRules: ['工单编号'],
    requiredColumns: ['工单编号', '产品编码', '计划数量'],
  },
  export: {
    loading: false,
  },
  pageInput: {
    currentPage: 1,
    pageSize: 20,
    filter: {},
    dynamicFilter: {},
  } as PageInputWorkOrderGetPageInput,
  workOrderListData: [] as Array<WorkOrderGetPageOutput>,
  filters: [
    {
      field: 'orderCode',
      operator: 'Contains',
      description: '工单编号',
      componentName: 'el-input',
      defaultSelect: true,
    },
    {
      field: 'orderName',
      operator: 'Contains',
      description: '工单名称',
      componentName: 'el-input',
      defaultSelect: false,
    }
  ] as Array<DynamicFilterInfo>,
})


onMounted(async () => {
  await onQuery();
  eventBus.off('refreshWorkOrder')
  eventBus.on('refreshWorkOrder', async () => {
    onQuery()
  })
})
onBeforeMount(() => {
  eventBus.off('refreshWorkOrder')
})

//查询分页
const onQuery = async () => {
  state.loading = true
  const res = await new WorkOrderApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })

  state.workOrderListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}
//高级查询
const onFilter = () => {
  myFilterDialogRef.value.open()
}

const onFilterSure = (dynamicFilter: any) => {
  state.pageInput.dynamicFilter = dynamicFilter
  onQuery()
}

//新增
const onAdd = () => {
  state.workOrderFormTitle = '新增工单信息'
  workOrderFormRef.value.open()
}
//导入
const onImport = () => {
  state.import.title = `导入工单数据`
  workOrderImportRef.value.open()
  onQuery()
}
//导出
const onExport = async () => {
  state.export.loading = true

  await new WorkOrderApi()
    .exportData(
      {
        dynamicFilter: state.pageInput.dynamicFilter,
        sortList: state.pageInput.sortList,
      },
      { format: 'blob', returnResponse: true }
    )
    .then((res: any) => {
      const contentDisposition = res.headers['content-disposition']
      const matchs = /filename="?([^;"]+)/i.exec(contentDisposition)
      let fileName = ''
      if (matchs && matchs.length > 1) {
        fileName = decodeURIComponent(matchs[1])
      } else {
        fileName = `数据工单列表${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
      }
      const a = document.createElement('a')
      a.download = fileName
      a.href = URL.createObjectURL(res.data as Blob)
      a.click()
      URL.revokeObjectURL(a.href)
    })
    .finally(() => {
      state.export.loading = false
    })
}
//修改
const onEdit = (row: WorkOrderGetOutput) => {
  state.workOrderFormTitle = '编辑工单信息'
  workOrderFormRef.value.open(row)
}

//删除
const onDelete = (row: WorkOrderGetOutput) => {
  proxy.$modal
    .confirmDelete(`确定要删除工单编号为【${row.orderCode}】?`)
    .then(async () => {
      await new WorkOrderApi().softDelete({ id: row.id }, { loading: true, showSuccessMessage: true })
      onQuery()
    })
    .catch(() => { })
}

const onSizeChange = (val: number) => {
  state.pageInput.currentPage = 1
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}
</script>